import React from 'react'

import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as pageActions from '../redux/action/index.js';

function Page(props) {

    // async_decrement 使用异步 action 需要使用中间件
    const { 
        name,
        age,
        users,
        increment,
        decrement,
        async_decrement,
        async_getUsers
    } = props
    const url = "http://127.0.0.1:3001/users"

    return (
        <div>
            <h2>Page：</h2>
            <div><span>name: {name}</span> <span>age: {age}</span></div>
            <div>users: </div>
            <div>{users.map(user => {
                return (
                    <div key={user.name + user.age}>
                        <p>name: {user.name}</p>
                        <p>age: {user.age}</p>
                    </div>
                )
            })}</div>

            <div>
                <button onClick={() => increment(10)}>加年龄</button>
                <button onClick={() => async_decrement(5)}>减年龄</button>
                <button onClick={() => async_getUsers(url)}>
                    Saga 异步获取数据
                </button>

            </div>
        </div>
    )
}

// 各种映射、绑定组件到 store
const mapStateToProps = state => ({
    ...state
});
  
const mapDispatchToProps = dispatch => bindActionCreators(pageActions, dispatch)
// ===> 等同于
// const mapDispatchToProps = dispatch => ({
//   increment (payload) {
//     dispatch(increment(payload))
//   },
//   decrement (payload) {
//     dispatch(decrement(payload))
//   }
// })
export default connect(mapStateToProps, mapDispatchToProps)(Page)
